package cn.easybuy.web.pre;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.easybuy.dao.CarDao;
import cn.easybuy.entity.Car;
import cn.easybuy.service.CarService;
import cn.easybuy.service.impl.CarServiceImpl;

public class BuyCarServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr=request.getParameter("opr");
		CarService carService=new CarServiceImpl();
		PrintWriter out =response.getWriter();
		Car car =new Car();
		
		if (opr.equals("addCar")) { 
			String name=request.getParameter("name");
			String price=request.getParameter("price");
			String color=request.getParameter("color");
			String number=request.getParameter("n_ipt");
			System.out.println("number="+number);
			List<Car> list =carService.getAllCars(name);
			car.setName(name);
			car.setProperty(color);
			if (list.size()>0) {
				for (Car car2 : list) {
					int num=car2.getNumber()+Integer.parseInt(number);
					car.setNumber(num);
					Double double1=Double.parseDouble(price)*num;
					System.out.println("double1="+double1);
					car.setTotalprice(Double.parseDouble(price)*num);
					
				}
			int mun1=carService.updateCar(car);
		
				
			}else {
				car.setNumber(Integer.parseInt(number));
				Double totalprice=Double.parseDouble(price)*(Integer.parseInt(number));
				car.setTotalprice(totalprice);
				carService.saveCar(car);
			}
			out.print("ok");
		}else if (opr.equals("showCar")) {
			List<Car> list =carService.getAllCarProduct();
			String carList=JSON.toJSONString(list);
			out.print(carList);
			
		}else if (opr.equals("del")) {
			String name=request.getParameter("name");
			int num =carService.deleteCar(name);
			if (num>0) {
				out.print("success");
			}
		}
		out.flush();
		out.close();
		
	}

}
